package com.fingard.dsp.bank.directbank.dbs01;

import com.fingard.util.TransIDHelper;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPSecretKey;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.dbs01.util.BouncyCastlePgpHelper;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;

import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by F on 2018/7/12.
 */
public class DBS01Base extends DirectBase {

    private String splitFlag = "-}\\$\\{";

    //tag of MT940&MT942
    private String tag20 = ":20:";
    private String tag25 = ":25:";
    private String tag28C = ":28C:";
    private String tag60F = ":60F:";
    private String tag61 = ":61:";
    private String tag86 = ":86:";
    private String tag62F = ":62F:";
    private String tag64 = ":64:";

    private String tag13D = ":13D:";
    private String tag34F = ":34F:";
    private String tag90D = ":90D:";
    private String tag90C = ":90C:";

    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String getCharset() {
        return "utf-8";
    }

    public List<String> downloadFile() throws Exception {

        List<String> fileList = new ArrayList<String>();
        String localhostSavePath = getBankConfig().getValueAsString("ReceiveFilePath");
        FileHelper.mkdir(localhostSavePath);
        FtpSet ftpSet = bankFront.getFtpSet("bat");
        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
//            Map<String, Object> jschMap = getChannel();
//            ChannelSftp channelSftp = (ChannelSftp) jschMap.get("channel");
//            Vector<ChannelSftp.LsEntry> vector = channelSftp.ls(bankFront.getFtpSet("bat").downDir);
//            channelSftp.cd(bankFront.getFtpSet("bat").downDir);
//            for (int i = 0; i < vector.size(); i++) {
//                String fileName = vector.get(i).getFilename();
//                if (fileName.contains("MT940") || fileName.contains("MT942") || fileName.contains("ACK")){
//                    channelSftp.get(fileName, localhostSavePath);
//                    fileList.add(fileName);
//                }
//            }
//        closeChannel(channelSftp,(Session)jschMap.get("session"));
        FtpReceiver receiver = sftpPortClient.downloadFile("", localhostSavePath);
        sftpPortClient.disconnect();
        if (receiver.isCompleted) {
            if (StringHelper.isNullOrEmpty(receiver.connMsg)) {
                WriteBankLogLn2("从银行下载的文件数量：0");
                return fileList;
            }
            fileList = Arrays.asList(receiver.connMsg.split("\\|"));
            String fileStr = receiver.connMsg.replaceAll("\\|", "\r\n");
            WriteBankLogLn2("从银行下载的文件数量：" + fileList.size() + "下载的文件： \r\n" + fileStr);

        }
        return fileList;

    }

    /**
     * 对明细记录进行数据落地处理
     *
     * @param allDetailContent 明细记录
     * @param accountNum       账号
     * @param balance          期初余额
     * @param date             支付当天 yyyyMMdd
     * @param cur              币种
     * @param fileType         文件类型('MT940','MT942')
     * @throws Exception
     */
    public void dealTransDetail(String[] allDetailContent, String accountNum, String balance, String date, String cur, String fileType) throws Exception {
        BigDecimal decimal = new BigDecimal(balance);
        String file = "";
        if ("MT942".equals(fileType)) {
            file = getBankConfig().getValueAsString("DealedPath") + File.separator + date + File.separator +
                    fileType + File.separator + accountNum + "_7515.txt";
        } else if ("MT940".equals(fileType)) {
            file = getBankConfig().getValueAsString("DealedPath") + File.separator + date + File.separator +
                    fileType + File.separator + accountNum + "_7516.txt";
        } else {
            throw new Exception("fileType参数不规范：" + fileType);
        }
        StringBuilder transDetail = new StringBuilder();
        for (String detailUnit : allDetailContent) {
            String tranTime = "";
            String tranDate = "";
//            String valueDate = "";
            String recAccName = "";
            String recAccBank = "";
            String recAccNum = "";
            String usage = "";
            String cdFlag = "";
            String accBal = "";
            String transAmt = "";
            String[] detailsplit = detailUnit.split(tag86);
            //交易日期
            tranDate = "20" + detailsplit[0].substring(0, 6);
            tranDate = Format.Date10Format.format(Format.Date8Format.parse(tranDate));
            //借贷标识
            if ('C' == detailsplit[0].charAt(10)) {
                cdFlag = "C";
            } else {
                cdFlag = "D";
            }
            int index = detailsplit[0].indexOf("N", 12);
            //交易金额
            transAmt = detailsplit[0].substring(12, index).replace(",", ".");
            if (transAmt.startsWith(".")) {
                transAmt = "0" + transAmt;
            }
            index = detailsplit[0].indexOf("?") + 1;
            //交易日期
            tranTime = detailsplit[0].substring(index, index + 6);
            tranTime = tranDate + " " + Format.Time8Format.format(Format.Time6Format.parse(tranTime));
            detailsplit = detailsplit[1].split("\\?");
            List<String> list = Arrays.asList(detailsplit);
            //借方金额增加，借方金额减少
            //借的明细才可能有返回值
            //受益人名称
            if (list.indexOf("BENM") != -1) {
                recAccName = list.get(list.indexOf("BENM") + 1).trim();
            }
            //受益人银行
            if (list.indexOf("BB") != -1) {
                recAccBank = list.get(list.indexOf("BB") + 1).trim();
            }
            //受益人账号
            if (list.indexOf("BA") != -1) {
                recAccNum = list.get(list.indexOf("BA") + 1).trim();
            }
            //借的明细才有可能有返回值
            //
            if (list.indexOf("OA") != -1) {
                recAccNum = list.get(list.indexOf("OA") + 1).trim();
            }
            if (list.indexOf("ORDP") != -1) {
                recAccName = list.get(list.indexOf("ORDP") + 1).trim();
            }
            if (list.indexOf("OB") != -1) {
                recAccBank = list.get(list.indexOf("OB") + 1).trim();
            }
            //支付说明
            if (list.indexOf("REMI") != -1) {
                usage = list.get(list.indexOf("REMI") + 1).trim();
            }
            //支付说明
            if (list.indexOf("OTH1") != -1) {
                usage = list.get(list.indexOf("OTH1") + 1).trim();
            }
            if (StringHelper.isNullOrEmpty(usage)) {
                usage = "没有获取支付说明";
            }
            if ("C".equals(cdFlag)) {
                decimal = decimal.add(new BigDecimal(transAmt));
            } else if ("D".equals(cdFlag)) {
                decimal = decimal.subtract(new BigDecimal(transAmt));
            }
            DecimalFormat format = new DecimalFormat("0.00");
//            账号 | 币种 | 交易日期| 交易时间| 计息日期 | 交易金额 |借贷标识| 账户余额 |对方账号|
//                    对方户名 | 对方银行 |用途
            String[] detail = new String[]{accountNum, cur, tranDate, tranTime, tranDate, transAmt, cdFlag,
                    format.format(decimal), recAccNum, recAccName, recAccBank, usage};
            for (int i = 0; i < detail.length; i++) {
                if (i < detail.length - 1) {
                    transDetail.append(detail[i].replaceAll("[\\r\\n]", "") + "|");
                } else {
                    transDetail.append(detail[i].replaceAll("[\\r\\n]", "") + "\r\n");
                }
            }
        }
        FileHelper.appendFile(file, transDetail.toString(), getCharset());
        WriteBankLogLn2("追加文件：" + file + ",追加明细内容 \r\n" + transDetail.toString());

    }


    protected boolean runCmd(String cmd) {
        String retCmdResult = "";
        BufferedReader bufferedReader = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String readLine;
            while ((readLine = bufferedReader.readLine()) != null) {
                retCmdResult = readLine;
            }
            process.destroy();
            return true;
        } catch (Exception ex) {
            WriteBankLogLn2("执行CMD异常" + ex.getMessage());
            return false;
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    protected boolean decryptFile(String fileName) {
        String decryptPath = getBankConfig().getValueAsString("DecryptPath") + File.separator;
        FileHelper.mkdir(decryptPath);
        String localhostSavePath = getBankConfig().getValueAsString("ReceiveFilePath") + File.separator + fileName;
        if (!FileHelper.existFile(localhostSavePath)) {
            WriteBankLogLn2("文件不存在：" + localhostSavePath);
            return false;
        }
        String decryptFile = decryptPath + fileName;
        //表示文件已经解析
        String passphrase = getBankConfig().getValueAsString("passphrase");
        String cmd = "gpg --passphrase " + passphrase + " -o " + decryptFile + " -d " + localhostSavePath;
        WriteBankLogLn2("执行CRM命令：" + cmd);
        synchronized (this) {
            runCmd(cmd);
            if (FileHelper.existFile(decryptFile)) {
                WriteBankLogLn2("解密报文成功：" + fileName);
                String successFilePath = getBankConfig().getValueAsString("SuccessFilePath") + File.separator
                        + Format.Date8Format.format(new Date()) + File.separator + "receive" + File.separator;
                FileHelper.mkdir(successFilePath);
                boolean flag = new File(localhostSavePath).renameTo(new File(successFilePath + fileName));
                if (flag) {
                    WriteBankLogLn2("文件：" + localhostSavePath + " ---移动至---\r\n" + successFilePath + fileName + "  成功");
                } else {
                    WriteBankLogLn2("文件：" + localhostSavePath + " ---移动至---\r\n" + successFilePath + fileName + "  失败");
                }
            } else {
                WriteBankLogLn2("解密报文失败：" + fileName);
                String exceptionFilePath = getBankConfig().getValueAsString("ExceptionFilePath") + File.separator
                        + Format.Date8Format.format(new Date()) + File.separator + "receive" + File.separator;
                FileHelper.mkdir(exceptionFilePath);
                boolean flag = new File(localhostSavePath).renameTo(new File(exceptionFilePath + fileName));
                if (flag) {
                    WriteBankLogLn2("文件：" + localhostSavePath + " ---移动至---\r\n" + exceptionFilePath + fileName + "  成功");
                } else {
                    WriteBankLogLn2("文件：" + localhostSavePath + " ---移动至---\r\n" + exceptionFilePath + fileName + "  失败");
                }
            }
            if (!FileHelper.existFile(decryptFile)) {
                return false;
            }
            return true;
        }
    }

    /**
     * 加密文件
     *
     * @param fileName 全路径名
     * @return
     */
    protected boolean encrypFile(String fileName) {
        String bankKey = getBankConfig().getValueAsString("BankKey");
        //String privateKey = getBankConfig().getValueAsString("PrivateKey");
        //String command = "gpg -o " +fileName+".gpg -eas -r "+privateKey+" -u "+bankKey+" "+fileName;
        String command = "gpg -o " + fileName + ".pgp -r " + bankKey + " -e " + fileName;
        WriteBankLogLn("执行CRM命令：" + command);
        runCmd(command);
        return FileHelper.existFile(fileName + ".pgp");
    }

    protected boolean uploadFile(String fullName) throws IOException {
        FtpSet ftpSet = bankFront.getFtpSet("bat");
        String upDir = ftpSet.upDir;
        File file = new File(fullName);
        String filename = upDir + File.separator + file.getName();
        filename = filename.replaceAll("\\\\", "/");
        FileInputStream inputStream = null;
        SftpPortClient sftpPortClient = null;
        try {
            sftpPortClient = new SftpPortClient(ftpSet);
            sftpPortClient.connectBySSH();
            inputStream = new FileInputStream(file);
//            ChannelSftp channelSftp = (ChannelSftp) jschMap.get("channel");
//            channelSftp.put(inputStream,filename);
            FtpReceiver receiver = sftpPortClient.uploadFile("", inputStream, filename);
            if (receiver.isCompleted) {
                WriteBankLogLn2("上传文件：" + filename + "成功");
            } else {
                WriteBankLogLn2("上传文件：" + filename + "失败");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            WriteBankLogLn("上传文件失败", e);
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            sftpPortClient.disconnect();
        }
        return true;
    }

    protected boolean exportContentToFile(String content, String fullName) {
        if (StringHelper.isNullOrEmpty(content) || StringHelper.isNullOrEmpty(fullName)) {
            return false;
        }
        try {
            FileHelper.writeFile(fullName, content, getCharset());
            WriteBankLogLn2("写入文件：" + fullName + ",文件内容 \r\n" + content);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return FileHelper.existFile(fullName);
    }

    protected void analysisMT940File(String fullName) throws Exception {
        //判断文件存不存在，不存在就不处理
        String context = FileHelper.readFileText(fullName, getCharset());
        if (StringHelper.isNullOrEmpty(context)) {
            WriteBankLogLn("文件解析失败：-------" + fullName);
            throw new Exception("读取文件内容异常：" + fullName);
        }
        WriteBankLogLn2("读取文件:" + fullName + "中的内容：\r\n" + context);
        String[] allAccUnit = context.toString().split(splitFlag);
        for (String accUnit : allAccUnit) {
            StringBuilder balanceContent = new StringBuilder();
            int tag61Start = accUnit.indexOf(tag61);
            int tag62FStart = accUnit.indexOf(tag62F);
            String allDetailContent = "";
            //如果有明细记录，就截取其中的明细长度，并去除原文中的明细长度
            if (tag61Start != -1) {
                tag61Start += tag61.length();
                allDetailContent = accUnit.substring(tag61Start, tag62FStart);
                accUnit = accUnit.replace(allDetailContent, "").replace(tag61, "");
            }
            int offset, endset;
            //获取账号
            offset = accUnit.indexOf(tag20) + tag20.length();
            endset = accUnit.indexOf(tag25);
            String accountNum = accUnit.substring(offset, endset).trim();
            //获取日初余额
            offset = accUnit.indexOf(tag60F) + tag60F.length();
            endset = accUnit.indexOf(tag62F);
            String openBal = accUnit.substring(offset, endset).replace(",", ".").trim();
            openBal = openBal.substring(10);
            if (openBal.startsWith(".")) {
                openBal = "0" + openBal;
            }
            offset = accUnit.indexOf(tag62F) + tag62F.length();
            endset = accUnit.indexOf(tag64);
            String banlanceEnd = accUnit.substring(offset, endset).trim();
            //获取日期
            String date1 = "20" + banlanceEnd.substring(1, 7);
//            String date = Format.Date10Format.format(Format.Date8Format.parse(date1));
            //获取币种
            String cur = banlanceEnd.substring(7, 10);
            //获取日终余额
            String banlance = banlanceEnd.substring(10).replace(",", ".").trim();
            if (banlance.startsWith(".")) {
                banlance = "0" + banlance;
            }
            offset = endset + tag64.length();
            String availBal = accUnit.substring(offset).trim().substring(10).replace(",", ".").replace("-}", "").trim();
            if (availBal.startsWith(".")) {
                availBal = "0" + availBal;
            }
//            账号|币种|当前余额|可用余额|昨日余额
            balanceContent.append(accountNum + "|").append(cur + "|").append(banlance + "|").append(availBal + "|").append(openBal);
            String dealedFile = getBankConfig().getValueAsString("DealedPath") + File.separator + date1 + File.separator
                    + "MT940" + File.separator + accountNum + "_7505.txt";
            FileHelper.writeFile(dealedFile, balanceContent.toString(), getCharset());
            WriteBankLogLn2("写入文件：" + dealedFile + ",文件内容 \r\n" + balanceContent.toString());
            //解析历史明细
            if (!StringHelper.isNullOrEmpty(allDetailContent)) {
                dealTransDetail(allDetailContent.split(tag61), accountNum, openBal, date1, cur, "MT940");
            }

        }
    }

    /**
     * 文件移到
     *
     * @param source 原地址
     * @param target 新地址
     * @return
     */
    protected boolean renameTo(String source, String target) {
        boolean flag = new File(source).renameTo(new File(target));
        if (flag) {
            WriteBankLogLn2("文件：" + source + " ---移动至---\r\n" + target + "  成功");
        } else {
            WriteBankLogLn2("文件：" + source + " ---移动至---\r\n" + target + "  失败");
        }
        return flag;
    }


    protected void analysisMT942File(String fullName) throws Exception {
        //判断文件存不存在，不存在就不处理
        String context = FileHelper.readFileText(fullName, getCharset());
        if (StringHelper.isNullOrEmpty(context)) {
            WriteBankLogLn("文件解析失败：-------" + fullName);
            throw new Exception("读取文件内容异常：" + fullName);
        }
        WriteBankLogLn2("读取文件:" + fullName + "中的内容：\r\n" + context);
        String[] allAccUnit = context.toString().split(splitFlag);
        for (String accUnit : allAccUnit) {
            StringBuilder balanceContent = new StringBuilder();
            int tag61Start = accUnit.indexOf(tag61);
            int tag90DStart = accUnit.indexOf(tag90D);
            int tag91CStart = accUnit.indexOf(tag90C);
            //判断明细后面是90D还是90c
            String flag = "";
            String allDetailContent = "";
            if (tag61Start != -1) {
                tag61Start += tag61.length();
                if (tag91CStart == -1) {
                    allDetailContent = accUnit.substring(tag61Start, tag90DStart);
                    flag = "D";
                } else if (tag90DStart == -1) {
                    allDetailContent = accUnit.substring(tag61Start, tag91CStart);
                    flag = "C";
                } else if (tag90DStart > tag91CStart) {
                    allDetailContent = accUnit.substring(tag61Start, tag91CStart);
                    flag = "C";
                } else if (tag90DStart < tag91CStart) {
                    allDetailContent = accUnit.substring(tag61Start, tag90DStart);
                    flag = "D";
                } else {
                    throw new Exception("报文格式有误");
                }
                accUnit = accUnit.replace(allDetailContent, "").replace(tag61, "");
            }

            int offset, endset;
            offset = accUnit.indexOf(tag20) + tag20.length();
            endset = accUnit.indexOf(tag25);
            String accountNum = accUnit.substring(offset, endset).trim();
            //账户当天的时间
            offset = accUnit.indexOf(tag13D) + tag13D.length();
            if ("C".equals(flag)) {
                endset = accUnit.indexOf(tag90C);
            } else if ("D".equals(flag)) {
                endset = accUnit.indexOf(tag90D);
            } else {
                endset = accUnit.indexOf(tag86);
            }

            String date = "20" + accUnit.substring(offset, endset).substring(0, 6);
            String date2 = accUnit.substring(offset, endset).substring(0, 10);//用于余额更新判断
            String tranDate = Format.Date10Format.format(Format.Date8Format.parse(date));
            //获取账户币种
            offset = accUnit.indexOf(tag34F) + tag34F.length();
            String cur = accUnit.substring(offset, offset + 3);

            //获取余额相关信息
            offset = accUnit.indexOf(tag86) + tag86.length();
            String balance = accUnit.substring(offset);
            offset = balance.indexOf("OPBL");
            endset = balance.indexOf("CLBL");
            String openBal = balance.substring(offset + 9, endset).replace(",", ".").trim();
            if (openBal.startsWith(".")) {
                openBal = "0" + openBal;
            }
            offset = balance.indexOf("CLAB");
            String closeBal = balance.substring(endset + 9, offset).replace(",", ".").trim();
            if (closeBal.startsWith(".")) {
                closeBal = "0" + closeBal;
            }
            String availBal = balance.substring(offset + 9).replace(",", ".").replace("-}", "").trim();
            if (availBal.startsWith(".")) {
                availBal = "0" + availBal;
            }
            String dealedPath = getBankConfig().getValueAsString("DealedPath") + File.separator + date + File.separator
                    + "MT942" + File.separator + accountNum + "_7506.txt";
            if (FileHelper.existFile(dealedPath)) {
                // 余额结果：账号|币种|当前余额|可用余额|期初余额|最后交易日期|文件生成时间|期初余额对应的日期
                String hisContent = FileHelper.readFileText(dealedPath, getCharset());
                String[] hisBal = hisContent.split("\\|");
                if (Double.valueOf(hisBal[hisBal.length - 2]) < Double.valueOf(date2)) {
                    //收到一个后生成的文件，除了期初余额和期初余额对应日期，与他都更新
                    balanceContent.append(accountNum + "|").append(cur + "|").append(closeBal + "|").append(availBal + "|")
                            .append(hisBal[4] + "|").append(tranDate + "|").append(date2 + "|").append(hisBal[7]);
                    FileHelper.writeFile(dealedPath, balanceContent.toString(), getCharset());
                    WriteBankLogLn2("更新文件：" + dealedPath + ",文件内容 \r\n" + balanceContent.toString());
                } else {
                    //收到一个先生成的文件，判断期初余额要不要更新
                    if (Double.valueOf(hisBal[hisBal.length - 1]) > Double.valueOf(date2)) {
                        // 余额结果：账号|币种|当前余额|可用余额|期初余额|最后交易日期|文件生成时间|期初余额对应的日期
                        balanceContent.append(hisBal[0] + "|").append(hisBal[1] + "|").append(hisBal[2] + "|").append(hisBal[3] + "|")
                                .append(openBal + "|").append(hisBal[5] + "|").append(hisBal[6] + "|").append(date2);
                        FileHelper.writeFile(dealedPath, balanceContent.toString(), getCharset());
                        WriteBankLogLn2("更新文件：" + dealedPath + ",文件内容 \r\n" + balanceContent.toString());
                    }

                }
            } else {
                balanceContent.append(accountNum + "|").append(cur + "|").append(closeBal + "|").append(availBal + "|")
                        .append(openBal + "|").append(tranDate + "|").append(date2 + "|" + date2);
                FileHelper.writeFile(dealedPath, balanceContent.toString(), getCharset());
                WriteBankLogLn2("写入文件：" + dealedPath + ",文件内容 \r\n" + balanceContent.toString());
            }
            //解析明细
            if (!StringHelper.isNullOrEmpty(allDetailContent)) {
                dealTransDetail(allDetailContent.split(tag61), accountNum, openBal, date, cur, "MT942");
            }
        }
    }

    protected void analysisFile(String fileName) {
        String date = Format.Date8Format.format(new Date());
        String decryptPath = getBankConfig().getValueAsString("DecryptPath") + File.separator;
        String successFilePath = getBankConfig().getValueAsString("SuccessFilePath") + File.separator + date + File.separator
                + "decrypt" + File.separator;
        FileHelper.mkdir(successFilePath);
        String exceptionPath = getBankConfig().getValueAsString("ExceptionFilePath") + File.separator + date + File.separator
                + "decrypt" + File.separator;
        FileHelper.mkdir(exceptionPath);
        String fullName = decryptPath + fileName;
        if (!FileHelper.existFile(fullName)) {
            return;
        }
        String[] result = null;
        WriteBankLogLn2("开始处理文件:" + fullName);
        try {
            if ((fileName.contains("ack") || fileName.contains("ACK")) && fileName.contains("UFF1.STP.")) {
                if (fileName.contains("ACK1.pgp") || fileName.contains("ack1.pgp")) {
                    result = analysisACK1File(fullName);
                } else if (fileName.contains("ACK2.pgp") || fileName.contains("ack2.pgp")) {
                    result = analysisACKFile(fullName, "ACK2");
                } else if (fileName.contains("ACK3.pgp") || fileName.contains("ack3.pgp")) {
                    result = analysisACKFile(fullName, "ACK3");
                }
                if (result == null || StringHelper.isNullOrEmpty(result[0]) ||
                        StringHelper.isNullOrEmpty(result[1]) || StringHelper.isNullOrEmpty(result[2])) {
                    throw new Exception("文件解析异常：-----" + fileName);
                }
                //获取支付请求日期
                String payReqDate = fileName.split("\\.")[4].substring(0, 8);
                String MsgId = result[0];
                String Status = result[1];
                /*
                 * 写入对应日期下，文件名为SEQ_ACK供1944查询
                 * */
                String dealedFilePath = getBankConfig().getValueAsString("DealedPath") + File.separator + payReqDate + File.separator + "ACK" + File.separator + MsgId + ".txt";
                if (!FileHelper.existFile(dealedFilePath)) {
                    String fileContent = MsgId + "|" + Status + "|" + result[2];
                    FileHelper.writeFile(dealedFilePath, fileContent, getCharset());
                    WriteBankLogLn2("写入文件：" + dealedFilePath + ",文件内容 \r\n" + fileContent);
                    renameTo(fullName, successFilePath + fileName);
                } else {
                    String fileContent = FileHelper.readFileText(dealedFilePath, getCharset());
                    if (Double.valueOf(fileContent.split("\\|")[2]) < Double.valueOf(result[2])) {
                        fileContent = MsgId + "|" + Status + "|" + result[2];
                        FileHelper.writeFile(dealedFilePath, fileContent, getCharset());
                        WriteBankLogLn2("更新文件：" + dealedFilePath + ",文件内容 \r\n" + fileContent);
                    }
                    renameTo(fullName, successFilePath + fileName);
                }
            } else if (fileName.contains("MT940")) {
                analysisMT940File(fullName);
                boolean flag = renameTo(fullName, successFilePath + fileName);
            } else if (fileName.contains("MT942")) {
                analysisMT942File(fullName);
                boolean flag = renameTo(fullName, successFilePath + fileName);
            } else {
                throw new Exception("文件类型不在范围：-----" + fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            renameTo(fullName, exceptionPath + fileName);
        }

    }


    protected String[] analysisACK1File(String fullName) throws Exception {
        String[] result = {"", "", ""};
        //  FileHelper.readFileText(fullName,getCharset());
//        BufferedReader reader =null;
//        String readline ="";
//        try {
//            InputStreamReader in = new InputStreamReader(new FileInputStream(fullName),"utf-8");
//            reader = new BufferedReader(in);
//            while((readline=reader.readLine())!=null){
//                if(readline.startsWith("HEADER")){
//                    break;
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//            WriteBankLogLn("文件读取异常：-------"+fullName);
//            return null;
//        }finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        String context = FileHelper.readFileText(fullName, getCharset());
        if (StringHelper.isNullOrEmpty(context)) {
            WriteBankLogLn2("文件解析失败：-------" + fullName);
            throw new Exception("读取文件内容异常：" + fullName);
        }
        WriteBankLogLn2("读取文件:" + fullName + "中的内容：\r\n" + context);
        context = context.substring(0, context.lastIndexOf("TRAILER"));
        String[] report = context.split(",");
        //从文件名中获取流水号
        result[0] = report[4].substring(11);
        //文件处理的时间
        result[2] = report[2].replaceAll(":", "").replaceAll("-", "").replaceAll("T", "");
        result[1] = "ACK1+" + report[9];
        WriteBankLogLn("文件解析成功：-------" + fullName);
        return result;
    }

    protected String[] analysisACKFile(String fullName, String fileType) throws Exception {
        String[] result = {"", "", ""};
//        BufferedReader reader = null;
//        try {
//             InputStreamReader in = new InputStreamReader(new FileInputStream(fullName),"utf-8");
//             reader = new BufferedReader(in);
//             String readLine;
//            while((readLine=reader.readLine())!=null){
//                if(readLine.startsWith("HEADER")){
//                    result[2] = readLine.split(",")[3].replaceAll("T","").replaceAll("-","").replaceAll(":","");
//                }
//                if(readLine.startsWith("DATA")) {
//                    String[] report =readLine.split(",");
//                    result[1] = fileType+"+"+report[11];
//                    result[0] =report[5];
//                    break;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        String context = FileHelper.readFileText(fullName, getCharset());
        if (StringHelper.isNullOrEmpty(context)) {
            WriteBankLogLn("文件解析失败：-------" + fullName);
            throw new Exception("读取文件内容异常：" + fullName);
        }
        WriteBankLogLn2("读取文件:" + fullName + "中的内容：\r\n" + context);
        int offset, endset;
        offset = 0;
        endset = context.indexOf("DATA");
        String header = context.substring(offset, endset);
        //获取文件生成时间
        result[2] = header.split(",")[3].replaceAll("T", "").replaceAll("-", "").replaceAll(":", "");
        offset = endset;
        endset = context.lastIndexOf("TRAILER");
        String data = context.substring(offset, endset);
        String[] report = data.split(",");
        //获取交易状态和流水号
        result[1] = fileType + "+" + report[11];
        result[0] = report[5];
        return result;
    }

    private static Object lockMutex = new Object();

    /**
     * 发送报文至银行
     *
     * @param p_reqStr 请求报文
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr, String typeName) throws Exception {
        synchronized (lockMutex) {
            if (getBankConfig().getValueAsInt("eachReqTimeWait") > 0) {
                Thread.sleep(TimeUnit.SECONDS.toMillis(getBankConfig().getValueAsInt("eachReqTimeWait")));
            } else {
                Thread.sleep(TimeUnit.SECONDS.toMillis(3));
            }
            String[] retStr = new String[]{"", ""};
            try {
                String url = StringHelper.trimEndFileSp(bankFront.serverURL) + "/" + typeName;
                WriteBankLogLn("1.提交银行的地址：" + url);
                String p_string = p_reqStr;
                WriteBankLogStep2(p_string);
                //PGP数据加密
                p_string = pgpEncryptSigned(p_string);
                WriteBankLogLn("PGP数据加密后请求银行的报文：" + p_string);
                //设置https协议
                System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
                WebRequest tmpWebRequest = new WebRequest(url);
                tmpWebRequest.setConnectTimeout(60000);
                tmpWebRequest.setRequestProperty("Host", bankFront.loginName);
                if (url.contains("payment")) {
                    tmpWebRequest.setRequestProperty("KeyId", getBankConfig().getValueAsString("payKeyId"));
                } else if(url.contains("status")){
                    tmpWebRequest.setRequestProperty("KeyId", getBankConfig().getValueAsString("statusKeyId"));
                } else if(url.contains("balance")){
                    tmpWebRequest.setRequestProperty("KeyId", getBankConfig().getValueAsString("selKeyId"));
                }
                tmpWebRequest.setRequestProperty("ORG_ID", bankFront.org);
                tmpWebRequest.setRequestProperty("Accept", "application/json");
                tmpWebRequest.setRequestProperty("Content-Type", "application/json");
                String charsetName = getCharset();
                byte[] tmpToWriteBytes = p_string.getBytes(charsetName);
                retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
                WriteBankLogStep3(retStr[1]);
                if (retStr[0].length() == 0) {
                    //PGP数据解密
                    retStr[1] = pgpDecryptAndVerify(retStr[1]);
                    WriteBankLogLn("PGP数据解密后银行响应的报文：" + retStr[1]);
                }
            } catch (Exception e) {
                WriteBankLogLn("请求到银行异常:" + e);
                retStr[0] = "E9999";
                retStr[1] = e.getMessage();
                e.printStackTrace();
            }
            return retStr;
        }
    }

    /**
     * PGP加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    protected String pgpEncryptSigned(String data) throws Exception {
        //银行公钥
        PGPPublicKey dbsPubKey = BouncyCastlePgpHelper.readPublicKey(new FileInputStream(getBankConfig().getValueAsString("dbsPubKey")));
        //客户私钥
        PGPSecretKey glpSecretKey = BouncyCastlePgpHelper.readSecretKey(new FileInputStream(getBankConfig().getValueAsString("glpPrivateKey")));
        PGPPrivateKey glpPrivateKey = BouncyCastlePgpHelper.findPrivateKey(new FileInputStream(getBankConfig().getValueAsString("glpPrivateKey")), getBankConfig().getValueAsString("passphrase").toCharArray());
        //加密
        return BouncyCastlePgpHelper.encryptSigned(data, dbsPubKey, glpSecretKey, glpPrivateKey);
    }

    /**
     * PGP解密
     *
     * @param signData
     * @return
     * @throws Exception
     */
    protected String pgpDecryptAndVerify(String signData) throws Exception {
        //银行公钥
        PGPPublicKey dbsPubKey = BouncyCastlePgpHelper.readPublicKey(new FileInputStream(getBankConfig().getValueAsString("dbsPubKey")));
        //客户私钥
        PGPPrivateKey glpPrivateKey = BouncyCastlePgpHelper.findPrivateKey(new FileInputStream(getBankConfig().getValueAsString("glpPrivateKey")), getBankConfig().getValueAsString("passphrase").toCharArray());
        //解密
        return BouncyCastlePgpHelper.decryptAndVerify(signData, glpPrivateKey, dbsPubKey);
    }
}